import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/event/new_order_event.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/module/waybill/page/waybill_detail_page.dart';
import 'package:flutter_rider/module/waybill/waybill_router.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../main/widgets/ext/u_text.dart';
import '../../../main/widgets/state/refreshable_layout.dart';
import '../../../main/widgets/ui_constant.dart';
import 'confirm_order_page.dart';

class BillWayPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return BillWayPageState();
  }
}

class BillWayPageState extends State<BillWayPage> {
  final _stateController = RefreshableLayoutController();
  final _inputController = TextEditingController(text: "");
  var _tabs = ["待确认", "履约中", "已完成", "已取消"];
  var _index = 0;
  late StreamSubscription _eventFn;
  // late StreamSubscription _eventFn2;

  @override
  void initState() {
    super.initState();

    _eventFn = eventBus.on<RefreshOrderEvent>().listen((event) {
      _stateController.reload();
    });
    // _eventFn2 = eventBus.on<NewOrderEvent>().listen((event) {
    //   _stateController.reload();
    // });
    _stateController.reload();
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn.cancel();
    // _eventFn2.cancel();
    _inputController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        color: UIColor.color_main,
        child: Column(
          children: [
            _renderTitle(),
            //_renderInput(),
            _renderTab(),
            Container(height: 0.5, color: Colors.black12),
            _renderList(),
          ],
        ));
  }

  String _buildUrl() {
    int status = 1;
    if (_tabs[_index] == '待确认') {
      status = 1;
    } else if (_tabs[_index] == '履约中') {
      status = 2;
    } else if (_tabs[_index] == '已完成') {
      status = 3;
    } else if (_tabs[_index] == '已取消') {
      status = -1;
    }
    var baseUrl = "/waybill/list?status=$status";
    var searchKey = _inputController.text.trim();
    if (searchKey.isNotEmpty) {
      if (!baseUrl.contains("?")) {
        baseUrl += "?";
      } else {
        baseUrl += "&";
      }
      baseUrl += "search_key=${Uri.encodeComponent(searchKey)}";
    }
    return baseUrl;
  }

  Widget _renderList() {
    return Expanded(
        child: RefreshableLayout(
            controller: _stateController,
            urlCallback: _buildUrl,
            itemBuilder: _renderListItem));
  }

  Widget _renderListItem(dynamic data, int index) {
    return GestureDetector(
      onTap: () {
        WaybillRouter.openWaybillDetail(context, data["waybill_no"]);
      },
      child: Container(
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        margin: EdgeInsets.only(top: 10.rpx),
        child: Column(
          children: [
            8.hspace,
            _renderItemTop(data),
            10.hspace,
            Container(height: 0.5.rpx, color: UIColor.color_divider),
            10.hspace,
            _renderSendAndRecv(data),
            data['status'] == 1 ? _renderCar(data) : 0.wspace,
            10.hspace,
            Container(height: 0.5.rpx, color: UIColor.color_divider),
            10.hspace,
            _renderTime(data),
            10.hspace,
          ],
        ),
      ),
    );
  }

  Widget _renderCar(dynamic data) {
    return Container(
        margin: EdgeInsets.only(top: 10.rpx),
        child: Row(
          children: [
            16.wspace,
            UText.get("履约车辆", UIColor.color_t7, 14.rpx).expand,
            UText.get("${data["car_no"]}", UIColor.color_primary, 14.rpx),
            16.wspace,
          ],
        ));
  }

  Widget _renderTime(dynamic data) {
    return Row(
      children: [
        16.wspace,
        UText.get("下单时间: " + data["creat_time"], UIColor.color_t8, 14.rpx)
            .expand,
        16.wspace,
      ],
    );
  }

  Widget _renderItemTop(dynamic data) {
    var st = data["status"];
    dynamic widget, bgColor, color, name;
    if (st == 1) {
      bgColor = const Color(0xffED7B2F);
      color = UIColor.color_content;
      name = "待确认";
    } else if (st == 2) {
      bgColor = const Color(0xff00A870);
      color = UIColor.color_content;
      name = "履约中";
    } else if (st == 3) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t9;
      name = "已完成";
    } else if (st == -1) {
      bgColor = UIColor.color_input;
      color = UIColor.color_t7;
      name = "已取消";
    } else {
      return widget = 0.wspace;
    }
    widget = Container(
      width: 66.rpx,
      height: 32.rpx,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(60), bottomLeft: Radius.circular(60)),
      ),
      child: UText.get(name, color, 14.rpx),
    );
    return Row(
      children: [
        16.wspace,
        Expanded(
            child: Row(children: [
          UText.get("运单编号：${data["waybill_no"]}", UIColor.color_t3, 14.rpx),
          4.wspace,
          GestureDetector(
            onTap: () {
              Clipboard.setData(ClipboardData(text: data["waybill_no"]));
              Tip.show("已复制到剪贴板");
            },
            child: SvgPicture.asset(
              R.image_text_copy,
              width: 16.rpx,
              height: 16.rpx,
            ),
          ),
        ])),
        widget,
      ],
    );
  }

  Widget _renderSendAndRecv(dynamic data) {
    return Row(
      children: [
        16.wspace,
        _renderSendCard(data),
        4.wspace,
        _renderArrow(),
        4.wspace,
        _renderRecvCard(data),
        16.wspace,
      ],
    );
  }

  Widget _renderArrow() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: 20.rpx,
      ),
      child: Row(
        children: [
          Expanded(child: Divider(color: UIColor.color_divider, height: 0.5.rpx)),
          SvgPicture.asset(R.image_line_arrow_right,
              width: 5.rpx, height: 5.rpx, color: UIColor.color_divider),
        ],
      ),
    );
  }

  Widget _renderSendCard(dynamic data) {
    return Container(
      width: 160.rpx,
      height: 64.rpx,
      decoration: BoxDecoration(
        color: UIColor.color_input,
        borderRadius: BorderRadius.circular(8.rpx),
      ),
      child: Row(
        children: [
          10.wspace,
          SvgPicture.asset(R.image_send, width: 24.rpx, height: 24.rpx),
          6.wspace,
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UText.get(data["pick_username"], UIColor.color_t1, 16.rpx,
                    overflow: TextOverflow.ellipsis),
                5.hspace,
                UText.get(data["pick_address"], UIColor.color_t5, 12.rpx,
                    overflow: TextOverflow.ellipsis),
              ],
            ),
          ),
        ],
      ),
    ).expand;
  }

  Widget _renderRecvCard(dynamic data) {
    return Container(
      width: 160.rpx,
      height: 64.rpx,
      decoration: BoxDecoration(
        color: UIColor.color_input,
        borderRadius: BorderRadius.all(Radius.circular(8.rpx)),
      ),
      child: Row(
        children: [
          10.wspace,
          SvgPicture.asset(R.image_get, width: 24.rpx, height: 24.rpx),
          6.wspace,
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UText.get(data["delivery_username"], UIColor.color_t1, 16.rpx,
                    overflow: TextOverflow.ellipsis),
                5.hspace,
                UText.get(data["delivery_address"], UIColor.color_t5, 12.rpx,
                    overflow: TextOverflow.ellipsis),
              ],
            ),
          ),
        ],
      ),
    ).expand;
  }

  Widget _renderTitle() {
    return Container(
      color: UIColor.color_content,
      width: double.infinity,
      height: MediaQuery.of(context).padding.top + 44.rpx,
      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
      child: Center(
          child: UText.get("运单中心", Colors.black, 16.rpx, fw: FontWeight.w600)),
    );
  }

  Widget _renderTab() {
    return Container(
      color: UIColor.color_content,
      child: Row(
        children: _tabs.asMap().keys.map((e) => _renderTabItem(e)).toList(),
      ),
    );
  }

  Widget _renderTabItem(int index) {
    var color =
        _index == index ? UIColor.color_primary : Colors.black.withOpacity(0.6);
    return Expanded(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          setState(() {
            _index = index;
            _stateController.reload();
          });
        },
        child: Column(
          children: [
            12.hspace,
            UText.get(_tabs[index], color, 16.rpx, fw: FontWeight.w600),
            3.hspace,
            Container(
              width: 24.rpx,
              height: 4.rpx,
              decoration: BoxDecoration(
                color: _index == index
                    ? UIColor.color_primary
                    : Colors.transparent,
                borderRadius: BorderRadius.all(Radius.circular(3.rpx)),
              ),
            ),
            3.hspace,
          ],
        ),
      ),
    );
  }
}
